﻿using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;
using System.Collections.Generic;
using System;
using Microsoft.Practices.Unity;

namespace Artech.PetShop.Common
{
    public class BaseTypeMatchingRuleData : MatchingRuleData
    {
        [ConfigurationProperty("matchs")]
        public NamedElementCollection<NameTypeConfigurationElement> Types
        {
            get
            {
                return (NamedElementCollection<NameTypeConfigurationElement>)this["matchs"];
            }
        }

        public override void ConfigurePolicy(PolicyDefinition policy, IConfigurationSource configurationSource)
        {
            List<Type> baseTypes = new List<Type>();
            foreach (var element in this.Types)
            {
                baseTypes.Add(element.Type);
            }

            if (baseTypes.Count == 0)
            {
                throw new ConfigurationErrorsException("No matched type configured!");
            }
            policy.AddMatchingRule<BaseTypeMatchingRule>(new InjectionMember[] { new InjectionConstructor(baseTypes) });
        }
    }
}
